package com.scs.application.core.mvc.controller;

import com.scs.application.core.utils.BeanValidators;
import com.scs.application.modules.sys.entity.Log;
import com.scs.application.modules.sys.service.LogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Validator;
/**
 * @Description： 基类controller
 */
public abstract class BaseController {
    @Autowired
    protected Validator validator;
    @Autowired
    protected LogService logService;
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 服务端参数有效性验证
     *
     * @param object 验证的实体对象
     * @param groups 验证组，不传入此参数时，同@Valid注解验证
     * @return 验证成功：继续执行；验证失败：抛出异常跳转400页面。
     */
    protected void beanValidator(Object object, Class<?>... groups) {
        BeanValidators.validateWithException(validator, object, groups);
    }


    /**sys_log表添加日志
     *
     * @param Log log
     */
    protected void logDb(Log log) {
        log.setMsg(log.getMsg());
        log.setParam(log.getParam());
        logService.save(log);
    }

    public HttpServletRequest request() {
        return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
    }
    public HttpServletResponse response() {
        return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getResponse();
    }
}
